package com.atguigu.gmall.pms.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.pms.entity.AttrEntity;
import com.atguigu.gmall.pms.entity.SkuEntity;
import com.atguigu.gmall.pms.mapper.AttrMapper;
import com.atguigu.gmall.pms.mapper.SkuMapper;
import com.atguigu.gmall.pms.vo.SaleAttrValueVo;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.mapper.SkuAttrValueMapper;
import com.atguigu.gmall.pms.entity.SkuAttrValueEntity;
import com.atguigu.gmall.pms.service.SkuAttrValueService;
import org.springframework.util.CollectionUtils;


@Service("skuAttrValueService")
public class SkuAttrValueServiceImpl extends ServiceImpl<SkuAttrValueMapper, SkuAttrValueEntity> implements SkuAttrValueService {

    @Autowired
    private AttrMapper attrMapper;
    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SkuAttrValueEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SkuAttrValueEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public List<SkuAttrValueEntity> querySearchSkuAttrValueByCidAndSkuId(Long cid, Long skuId) {
        //根据cid  和 search_type=1查询 Attr 表的id集合
        List<AttrEntity> attrEntities = this.attrMapper.selectList(new QueryWrapper<AttrEntity>().eq("search_type", 1).eq("category_id", cid));
        //根据这个实体类获得主键id的集合
        if (CollectionUtils.isEmpty(attrEntities)) {
            return null;
        }
        List<Long> attrIds = attrEntities.stream().map(AttrEntity::getId).collect(Collectors.toList());
        //根据ids和skuId 获得 attrValue
        //SELECT * FROM pms_sku_attr_value WHERE sku_id=1 AND attr_id IN (4,5,6,8,9)
        List<SkuAttrValueEntity> attrValueEntities = this.list(new QueryWrapper<SkuAttrValueEntity>().eq("sku_id", skuId).in("attr_id", attrIds));


        return attrValueEntities;
    }

    /**
     * 根据SpuId 查询sku下所有的销售属性
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SaleAttrValueVo> querySkuSaleAttrValueBySpuId(Long spuId) {
        // 查询所有的sku
        List<SkuEntity> skuEntities = this.skuMapper.selectList(new QueryWrapper<SkuEntity>().eq("spu_id", spuId));
        if (CollectionUtils.isEmpty(skuEntities)) {
            return null;
        }
        //查询sku的ids集合
        List<Long> skuIds = skuEntities.stream().map(SkuEntity::getId).collect(Collectors.toList());

        //根据skuIds查询sku的所有销售属性
//        List<SkuAttrValueEntity> skuAttrValueEntities = this.list(new QueryWrapper<SkuAttrValueEntity>().in("sku_id", skuIds));

        // 根据skuIds集合查询销售属性集合
        List<SkuAttrValueEntity> skuAttrValueEntities = this.list(new QueryWrapper<SkuAttrValueEntity>().in("sku_id", skuIds));
        if (CollectionUtils.isEmpty(skuAttrValueEntities)){
            return null;
        }

        // 把销售属性集合转化成SaleAttrValueVo集合
        List<SaleAttrValueVo> saleAttrValueVos = new ArrayList<>();
        // 以attrId作为key， 以attrId相同的数据作为value
        Map<Long, List<SkuAttrValueEntity>> map = skuAttrValueEntities.stream().collect(Collectors.groupingBy(SkuAttrValueEntity::getAttrId));
        map.forEach((attrId, skuAttrValues) -> {
            SaleAttrValueVo saleAttrValueVo = new SaleAttrValueVo();
            saleAttrValueVo.setAttrId(attrId);
            // 只要有这个分组，skuAttrValues至少会有一个元素
            saleAttrValueVo.setAttrName(skuAttrValues.get(0).getAttrName());
            Set<String> attrValues = skuAttrValues.stream().map(SkuAttrValueEntity::getAttrValue).collect(Collectors.toSet());
            saleAttrValueVo.setAttrValues(attrValues);
            saleAttrValueVos.add(saleAttrValueVo);
        });
        /*//{attrId:4,attrName:颜色,attrValue:'暗夜','苍雪','紫耀'} {attrId:5,attrName:内存,attrValue:'4G','8G','12G'} {attrId:6,attrName:存储,attrValue:'128','256','512'}
        //将 List<SkuAttrValueEntity> -->Map<attrId,List<SkuAttrValueEntity>>--> List<SaleAttrValueVo>
        // Map<attrId,List<SkuAttrValueEntity>> 以相同的AttrId作为key,多条SkuAttrValueEntity记录(sku_attr的一行)作为value
        // 此时map中的数据条数与Vo集合数据条数一致                                                                                错误点getId
        Map<Long, List<SkuAttrValueEntity>> map = skuAttrValueEntities.stream().collect(Collectors.groupingBy(SkuAttrValueEntity::getAttrId));
        List<SaleAttrValueVo> attrValueVos = new ArrayList<>();
        // 遍历map集合 内部有两个key
        map.forEach((attrId, AttrValueEntity) -> {
            SaleAttrValueVo saleAttrValueVo = new SaleAttrValueVo();

            saleAttrValueVo.setAttrId(attrId);
            saleAttrValueVo.setAttrName(AttrValueEntity.get(0).getAttrName());
            // attrValue:'暗夜','苍雪','紫耀'  attrValue:'4G','8G','12G'  attrValue:'128','256','512'  将一个AttrValueEntity集合转为set集合
            saleAttrValueVo.setAttrValues(AttrValueEntity.stream().map(SkuAttrValueEntity::getAttrName).collect(Collectors.toSet()));
                                                                                               getAttrName应为getAttrValue
            attrValueVos.add(saleAttrValueVo);
        });*/
        return saleAttrValueVos;
    }

    /**
     * 根据spuId查询spu下所有销售属性与skuId的映射关系map
     *
     * @param spuId
     * @return {'苍青,8G,128G':101},{'清橘,12G,128G':102}
     */
    @Override
    public String querySaleWithSkuIdMappingBySpuId(Long spuId) {
        // 根据spuId 查询spu下所有的sku信息
        List<SkuEntity> skuEntities = this.skuMapper.selectList(new QueryWrapper<SkuEntity>().eq("spu_id", spuId));
        if (CollectionUtils.isEmpty(skuEntities)) {
            return null;
        }
        // 根据sku获取skuIds 集合
        List<Long> skuIds = skuEntities.stream().map(SkuEntity::getId).collect(Collectors.toList());
        // 查询到映射关系  mapList = [{sku_id=22, attr_values=白色,8G,256G}, {sku_id=23, attr_values=白色,12G,256G}]
        List<Map<String, Object>> mapList = this.skuAttrValueMapper.queryMappingBySkuIds(skuIds);

        // 需要将 其转为 {'苍青,8G,128G':101},{'苍青,12G,128G':102}
        if (CollectionUtils.isEmpty(mapList)) {
            return null;
        }
        // 转为map对象 结构应为{101:'苍青,8G,128G'}                                                                       map -> (Long) map.get("sku_id")));
        Map<String, Object> mapMapping = mapList.stream().collect(Collectors.toMap(map -> map.get("attr_values").toString(), map -> (Long)map.get("sku_id")));

        // 集合转换为json字符串
        return JSON.toJSONString(mapMapping);
    }

}